package com.yima.baseproj.utils.wx.weapp;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.yima.baseproj.utils.wx.weapp.model.AccessTokenModel;
import com.yima.baseproj.utils.wx.weapp.model.UserPhoneModel;
import com.yima.baseproj.config.redis.RedisUtil;
import com.yima.baseproj.utils.wx.weapp.model.Code2SessionModel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 * @Author 一码
 * @createDate 2023/4/1 09:00
 * @contact 1424529270@qq.com
 */
@Slf4j
public class WxUtil {

    /**
     * 登录凭证校验。通过 wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程.
     * 可以获取到unionid
     * @param code
     * @return
     */
    public static Code2SessionModel getJscode2session(String code){
        String url = String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", WxWeappConfig.APP_ID, WxWeappConfig.SECRET,code);
        String result = HttpUtil.get(url);
        log.info("登录凭证校验:{}",result);
        Code2SessionModel code2SessionModel = Code2SessionModel.objectFromData(result);

        return code2SessionModel;
    }

    /**
     * 获取手机号
     * 可以获取到unionid
     * @param code
     * @return
     */
    public static UserPhoneModel getUserPhonenumber(String code){
        String accessToken = getAccessToken();
        if(StringUtils.isBlank(accessToken)){
            return null;
        }
        String url = String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s",accessToken);
        Map<String, Object> params = MapUtil.newHashMap();
        params.put("code",code);
        String result = HttpUtil.post(url,JSON.toJSONString(params));
        if(StringUtils.isBlank(result)){
            return null;
        }
        UserPhoneModel userPhoneModel = UserPhoneModel.objectFromData(result);

        return userPhoneModel;
    }

    /**
     * 接口调用凭证：AccessToken
     * @return
     */
    public static String getAccessToken(){
        String accessToken = (String) RedisUtil.getNormalValue(WxWeappConfig.REDIS_ACCESS_TOKEN);
        if(StringUtils.isBlank(accessToken)){
            String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", WxWeappConfig.APP_ID, WxWeappConfig.SECRET);
            String result = HttpUtil.get(url);
            log.info(String.format("接口调用凭证:%s",result));
            if(StringUtils.isNotBlank(result)){
                AccessTokenModel accessTokenModel = AccessTokenModel.objectFromData(result);
                if(accessTokenModel.getErrcode() == 0){
                    RedisUtil.setTimeNormalKey(WxWeappConfig.REDIS_ACCESS_TOKEN, accessTokenModel.getAccess_token(), accessTokenModel.getExpires_in() + 0l, TimeUnit.SECONDS);
                    return accessTokenModel.getAccess_token();
                }
            }
        }

        return accessToken;
    }

    public static void main(String[] args) {
        getAccessToken();
        String accessToken = "55_KZf17yDUbH54Tx1FPcYirDzvsjFgPXbBXKr1Yt1ihVCp4f49Za80CH6dBcKGzd4HTLeem6xXA5xvNbimh9rjyiPU2nf1-7RNj7wNz3WP_Goa8PGOoum7-REnQtFv79MSrXCPfro5jJw0I9fDRNAjABAMIV";
        //测试openId:orMAk5PQuSopYeGbeVDaxvmIRpc4
        String openId = "orMAk5PQuSopYeGbeVDaxvmIRpc4";
//        WxWeappUtil.getInstance().uniformMessageSend(openId,);
    }

}